﻿MPT.addClass("EditAvatar", function(_elm) {

    var upload_jQ = $('.e_upload', _elm);
    var hint_jQ = $('.e_hint', _elm);
    var avatar_jQ = $('.e_avatar', _elm);
    var roll_r_jQ = $('.e_roll_r', _elm);
    var roll_l_jQ = $('.e_roll_l', _elm);
    var drag_jQ = $('.e_drag', _elm);
    var drag_in_jQ = $('.e_drag_in', _elm);
    var zoom_jQ = $('.e_zoom', _elm);
    var submit_jQ = $('.e_submit', _elm);
    var skip_jQ = $('.e_skip', _elm);

    var load_img_jQ = $('#load_img', _elm);
    var pre_jQ = $('#pre', _elm);
    var tiny_jQ = $('#tiny', _elm);
    var small_jQ = $('#small', _elm);

    var PRE_SMALL_SIDE = 100, PRE_TINY_SIDE = 50;
    var MAX_W = MAX_H = MAX_S = 250;
    var MASK_BORDER = 300, AVATAR_BORDER = 3, DRAG_BORDER = 1;

    //旋转角度，为滤镜服务,适用于IE家族。
    var rotate_angle;

    upload_jQ.change(function() {

        if (!fileValidate(this.value)) {

            hint_jQ.html("只能上传JPG、JPEG、PNG图片格式");
            //initPreview();

        } else {

            hint_jQ.html("");
            upload_img = new UploadImage(this, 200000);
            if (!upload_img.checkSize()) {
                hint_jQ.html("文件不能超过200K");
                //initPreview();
            } else {
                hint_jQ.html("");
                //$(".e_file_path_text").html(jQuery(this).val()).css('overflow', "hidden");
            }
        }
    });



    var fileValidate = function(_str) {

        return (new RegExp(".*\.jpg|png|jpeg$")).test(_str.toLowerCase());
    };


    //获取图片缩放后的长度、宽度、左位移、上位移、缩放比例
    var getPreScale = function(_width, _height) {

        var width = _width;
        var height = _height;
        var init_left, init_top, scale_ratio;

        var max_side = width > height ? width : height;

        if (max_side > MAX_S) {

            if (width > height) {
                scale_ratio = MAX_W / width;
                init_left = 0;
                init_top = (MAX_H - Math.round(height * scale_ratio)) / 2;

                width = MAX_W;
                height = Math.round(height * scale_ratio);

            } else {
                scale_ratio = MAX_H / height;
                init_top = 0;
                init_left = (MAX_W - Math.round(width * scale_ratio)) / 2;

                height = MAX_H;
                width = Math.round(width * scale_ratio);
            }
        } else {
            init_top = (MAX_H - height) / 2;
            init_left = (MAX_W - width) / 2;
            scale_ratio = 1;
        }

        $('#ratio', _elm).val(scale_ratio);
        $('#rotate', _elm).val(0);

        return { "width": width, "height": height, "top": init_top, "left": init_left };

    }

    var initDragScale = function(_w, _h) {

        //设置拖拽框的初始大小和位移
        var min_side = _w < _h ? _w : _h;
        var drag_side = min_side;
        var drag_off = (MAX_S - min_side) / 2;
        drag_jQ.css({ "height": drag_side, "width": drag_side, "top": drag_off, "left": drag_off });
        drag_in_jQ.css({ "height": drag_side - DRAG_BORDER * 2, "width": drag_side - DRAG_BORDER * 2 });

        var drag_top = (_h - drag_side) / 2;
        var drag_left = (_w - drag_side) / 2;

        setSmallScale(min_side, drag_top, drag_left, _w, _h);
    }

    var setSmallScale = function(_drag_side, _drag_t, _drag_l, _pre_w, _pre_h) {

        var small_boxs = { "small": PRE_SMALL_SIDE, "tiny": PRE_TINY_SIDE };

        $.each(small_boxs, function(_e, _s) {

            var ratio_small = _drag_side / _s;

            var small_h = Math.round(_pre_h / ratio_small);
            var small_w = Math.round(_pre_w / ratio_small);
            var small_l = -Math.round(_drag_l / ratio_small);
            var small_t = -Math.round(_drag_t / ratio_small);

            //滤镜旋转使用原始高宽，故在90/270度的时候，需要将高宽颠倒
            if (rotate_angle != undefined && (rotate_angle == 90 || rotate_angle == 270)) {
                var temp = small_h;
                small_h = small_w;
                small_w = temp;
            }

            $('#' + _e, _elm).css({ "height": small_h, "width": small_w, "top": small_t, "left": small_l });
        });

        $('#width', _elm).val(_drag_side);
        $('#height', _elm).val(_drag_side);
        $('#cutX', _elm).val(parseInt(_drag_l));
        $('#cutY', _elm).val(parseInt(_drag_t));
    };

    var initPreview = function(_src, _scale) {

        pre_jQ.replaceWith('<img id="pre" angle="0">');
        tiny_jQ.replaceWith('<img id="tiny" angle="0">');
        small_jQ.replaceWith('<img id="small" angle="0">');

        pre_jQ = $('#pre', _elm);
        tiny_jQ = $('#tiny', _elm);
        small_jQ = $('#small', _elm);

        pre_jQ.attr("src", _src);
        tiny_jQ.attr("src", _src);
        small_jQ.attr("src", _src);

        pre_jQ.css({ "height": _scale.height, "width": _scale.width, "margin-top": _scale.top, "margin-left": _scale.left }).show();
    }

    var UploadImage = function(_upload, _max_size) {

        var check_size = true;

        if (typeof FileReader == 'undefined') {
            if (_max_size) {
                try {
                    var image = new Image();
                    image.dynsrc = _upload.value;
                    var filesize = image.fileSize
                } catch (err) {
                    var filesize = 1;
                }
                if (filesize > _max_size || filesize <= 0) {
                    check_size = false;
                }
            }
            if (check_size) {

                load_img_jQ.attr('src', _upload.value);

                var width = load_img_jQ.width();
                var height = load_img_jQ.height();
                var scale = getPreScale(width, height);

                initPreview(_upload.value, scale);
                initDragScale(scale.width, scale.height);
            }
        }
        else {
            if (_max_size) {
                var filesize = _upload.files[0]['size'];
                if (filesize > _max_size || filesize <= 0) {
                    check_size = false;
                }
            }
            if (check_size) {
                var reader = new FileReader();
                reader.readAsDataURL(_upload.files[0]);
                reader.onloadend = function(_e) {

                    load_img_jQ.attr('src', _e.target.result);

                    load_img_jQ.load(function() {
                        var width = load_img_jQ.width();
                        var height = load_img_jQ.height();
                        var scale = getPreScale(width, height);

                        initPreview(_e.target.result, scale);
                        initDragScale(scale.width, scale.height);
                    });
                };
            }
        }

        this.checkSize = function() {
            return check_size;
        };
    }


    roll_r_jQ.click(function() {
        rotate(-90);
    });

    roll_l_jQ.click(function() {
        rotate(90);
    });

    var filterRotate = function(_new_angel, _sintheta, _costheta) {

        //bool表示是否做位置修正，小头像预览没有父元素，不需要作修正
        var pres = { "pre": true, "small": false, "tiny": false };
        rotate_angle = _new_angel;

        $.each(pres, function(_e, _fix) {

            var p = $('#' + _e, _elm);
            p.attr("angle", _new_angel);

            //使用滤镜做翻转，使用原始高度和宽度，所以不需要颠倒高度和宽度
            p.css("filter", "progid:DXImageTransform.Microsoft.Matrix(M11=" + _costheta + ",M12=" + (-_sintheta) + ",M21=" + _sintheta + ",M22=" + _costheta + ",SizingMethod='auto expand')");

            //---------------颠倒偏移量--------------------
            if (_fix) {
                var p_top = p.css('margin-top');
                var p_left = p.css('margin-left');
                p.css({ "margin-top": p_left, "margin-left": p_top });
            }
            else {
                var p_top = p.css('top');
                var p_left = p.css('left');
                p.css({ "top": p_left, "left": p_top });
            }
        });
    };

    var canvasRotate = function(_new_angle, _rotation) {

        //原始上传图的图源和大小
        var origin_src = load_img_jQ.attr('src');
        var origin_height = load_img_jQ.height();
        var origin_width = load_img_jQ.width();

        //bool表示是否做画布大小的修正
        var pres = { "pre": true, "small": false, "tiny": false };

        $.each(pres, function(_e, _fix) {

            var p = $('#' + _e, _elm);

            //---------------参数调整------------------------------------------------------
            var base_x, base_y;
            var canvas_h = origin_height;
            var canvas_w = origin_width;

            if (_new_angle == 90) {

                base_x = origin_height;
                base_y = 0;
                canvas_h = origin_width;
                canvas_w = origin_height;

            } else if (_new_angle == 180) {

                base_x = origin_width;
                base_y = origin_height;

            } else if (_new_angle == 270) {

                base_x = 0;
                base_y = origin_width;
                canvas_h = origin_width;
                canvas_w = origin_height;
            } else {  //360度

                base_x = 0;
                base_y = 0;
            }

            //---------------创建Canvas------------------------------------------------------
            var canvas = document.createElement('canvas');

            //Canvas的内置图像每次都采用最原始的上传图
            if (!p[0].oImage) {
                canvas.oImage = new Image();
                canvas.oImage.src = origin_src;
                canvas.oImage.width = origin_width;
                canvas.oImage.height = origin_height;

            } else {
                canvas.oImage = p[0].oImage;
            }

            canvas.height = canvas_h;
            canvas.width = canvas_w;

            var context = canvas.getContext('2d');
            context.save();
            context.translate(base_x, base_y);
            context.rotate(_rotation);
            context.drawImage(canvas.oImage, 0, 0, canvas.oImage.width, canvas.oImage.height);
            context.restore();


            //---------------颠倒高度、宽度、偏移量，替换图像------------------------------------------------------

            $(canvas).attr("id", p.attr("id"));
            $(canvas).attr("angle", _new_angle);
            $(canvas).css({ "height": p.width(), "width": p.height() });

            if (_fix) {
                var p_top = p.css('margin-top');
                var p_left = p.css('margin-left');
                $(canvas).css({ "margin-top": p_left, "margin-left": p_top });
            }
            else {
                var p_top = p.css('top');
                var p_left = p.css('left');
                $(canvas).css({ "top": p_left, "left": p_top });
            }

            p.replaceWith(canvas);
        });

        //Canvas旋转会替代原有元素，所以旋转完成后重新获取元素
        pre_jQ = $('#pre', _elm);
        tiny_jQ = $('#tiny', _elm);
        small_jQ = $('#small', _elm);
    };

    var rotate = function(angle) {

        //获取旋转相关的四个参数：角度、弧度、正弦、余弦
        var new_angel = (parseInt(pre_jQ.attr("angle")) + angle + 360) % 360;
        var rotation = Math.PI * new_angel / 180;
        var costheta = Math.round(Math.cos(rotation));
        var sintheta = Math.round(Math.sin(rotation));

        $('#rotate', _elm).val(new_angel);

        //分滤镜和Canvas两种方式旋转
        if (document.all && !window.opera) {

            filterRotate(new_angel, sintheta, costheta);
        } else {

            canvasRotate(new_angel, rotation);
        }

        initDragScale(pre_jQ.width(), pre_jQ.height());
    };

    $('.e_drag', _elm).mousedown(function(e) {

        //拖拽的原始偏移量
        var oldLeft = (drag_jQ.offset().left + MASK_BORDER) - (avatar_jQ.offset().left + AVATAR_BORDER);
        var oldTop = (drag_jQ.offset().top + MASK_BORDER) - (avatar_jQ.offset().top + AVATAR_BORDER);

        //鼠标按下时，鼠标的绝对坐标
        var oldEventX = e.pageX;
        var oldEventY = e.pageY;

        //拖放框的原始高度宽度，+2进行边框修正
        var originH = drag_jQ.height();
        var originW = drag_jQ.width();

        //预览图的原始偏移量
        var originL = pre_jQ.offset().left - (avatar_jQ.offset().left + AVATAR_BORDER);
        var originT = pre_jQ.offset().top - (avatar_jQ.offset().top + AVATAR_BORDER);

        e.stopPropagation();

        $(document).bind('mousemove', function(e) {

            //鼠标移动到某点时，在横坐标和纵坐标方向上的偏移量
            var deltaLeft = e.pageX - oldEventX;
            var deltaTop = e.pageY - oldEventY;

            //鼠标移动到某点时，计算出相对父容器的新的偏移量
            var newLeft = oldLeft + deltaLeft;
            var newTop = oldTop + deltaTop;

            //偏移量的界限，防止超出图片的位置
            var topLimit = originT;
            var leftLimit = originL;
            var bottomLimit = originT + (pre_jQ.height() - originH);
            var rightLimit = originL + (pre_jQ.width() - originW);

            if (newTop < topLimit) { newTop = topLimit; }
            else if (newTop > bottomLimit) { newTop = bottomLimit; }

            if (newLeft < leftLimit) { newLeft = leftLimit; }
            else if (newLeft > rightLimit) { newLeft = rightLimit; }

            drag_jQ.css({ "top": newTop, "left": newLeft });

            setSmallScale(originH, newTop - topLimit, newLeft - leftLimit, pre_jQ.width(), pre_jQ.height());

            e.stopPropagation();
        });
    });

    $('.e_drag', _elm).mouseup(function(e) {

        $(document).unbind('mousemove');
    });

    $('.e_zoom', _elm).mousedown(function(e) {

        //鼠标按下时，鼠标的绝对坐标
        var oldEventX = e.pageX;
        var oldEventY = e.pageY;

        //相对父容器的原始偏移量
        var oldLeft = (drag_jQ.offset().left + MASK_BORDER) - (avatar_jQ.offset().left + AVATAR_BORDER);
        var oldTop = (drag_jQ.offset().top + MASK_BORDER) - (avatar_jQ.offset().top + AVATAR_BORDER);

        //拖放框的原始边长
        var oldSide = drag_jQ.height();

        e.stopPropagation();

        $(document).bind('mousemove', function(e) {

            //鼠标移动到某点时，在横坐标和纵坐标方向上的偏移量
            var deltaLeft = e.pageX - oldEventX;
            var deltaTop = e.pageY - oldEventY;

            //边长的最小值和最大值，防止图片过小或者缩放框超出图片边界
            var minSide = 30;
            var maxSide = 30;

            //两个方向上，取最大的偏移量，作为边长的变化
            var maxDelta = deltaLeft > deltaTop ? deltaLeft : deltaTop;

            var newSide = oldSide + maxDelta;

            //新的边长不能小于最小边长
            newSide = newSide > minSide ? newSide : minSide;

            //两个方向上，边长能扩展的最大额度
            var maxY = (avatar_jQ.height() + pre_jQ.height()) / 2 - oldTop;
            var maxX = (avatar_jQ.width() + pre_jQ.width()) / 2 - oldLeft;

            maxSide = maxX < maxY ? maxX : maxY;

            newSide = newSide < maxSide ? newSide : maxSide;

            //将新的边长赋给拖拽框
            drag_jQ.css({ "height": newSide, "width": newSide });
            drag_in_jQ.css({ "height": newSide - DRAG_BORDER * 2, "width": newSide - DRAG_BORDER * 2 });

            setSmallScale(newSide, (drag_jQ.offset().top + MASK_BORDER) - pre_jQ.offset().top, (drag_jQ.offset().left + MASK_BORDER) - pre_jQ.offset().left, pre_jQ.width(), pre_jQ.height());

            e.stopPropagation();
        });
    });

    $(document).mouseup(function() {
        $(document).unbind('mousemove');
    });

    skip_jQ.click(function() {

        window.location.hash = MPT.Config["hash"]["myspace"];
    });
});
